package com.leizi.igym.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leizi.igym.constant.EmployeeConstant;
import com.leizi.igym.domain.Trainer;
import com.leizi.igym.dto.TrainerAddDTO;
import com.leizi.igym.dto.TrainerDTO;
import com.leizi.igym.dto.TrainerPageQueryDTO;
import com.leizi.igym.enums.FileUploadBizEnum;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.manager.CosManager;
import com.leizi.igym.resp.PageResult;
import com.leizi.igym.resp.Result;
import com.leizi.igym.service.TrainerService;
import com.leizi.igym.utils.COSUtils;
import com.leizi.igym.utils.ThrowUtils;
import com.leizi.igym.vo.TrainerVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @Author: leizi0110
 * @CreateTime: 2024-04-05  17:48
 * @Description:
 */

@RestController("adminTrainerController")
@RequestMapping("/admin/trainer")
@Tag(name = "管理端-教练相关接口")
@Slf4j
public class TrainerController {

    @Resource
    private TrainerService trainerService;

    @Resource
    private CosManager cosManager;

    @Operation(summary = "管理端：新增教练信息")
    @PostMapping
    public Result addTrainer(@RequestBody TrainerAddDTO dto) {
        log.info("管理端正在添加教练信息，教练信息为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        boolean result = trainerService.saveInAdmin(dto);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.OPERATION_ERROR, "添加教练信息失败！");
        }
        return Result.ok(result);
    }

    @Operation(summary = "管理端：删除教练信息")
    @DeleteMapping("{id}")
    public Result deleteTrainer(@PathVariable("id") Long id) {
        log.info("管理端正在删除教练信息，教练id为：{}", id);
        ThrowUtils.throwIf(Objects.isNull(id) || id <= 0, ReturnCodeEnum.PARAMS_ERROR);
        boolean result = trainerService.deleteTrainerInAdmin(id);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "删除教练信息失败！");
        }
        return Result.ok(result);
    }

    @Operation(summary = "管理端：批量删除教练信息")
    @DeleteMapping("batch")
    public Result deleteBatch(@RequestBody List<Long> ids) {
        log.info("管理端正在批量删除教练信息，教练们的id为：{}", ids);
        ThrowUtils.throwIf(CollectionUtil.isEmpty(ids), ReturnCodeEnum.PARAMS_ERROR);
        boolean result = trainerService.deleteTrainerBatchInAdmin(ids);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "删除教练信息失败！");
        }
        return Result.ok(result);
    }

    @Operation(summary = "管理端：修改教练信息")
    @PutMapping("{id}")
    public Result modifyTrainer(@PathVariable("id") Long id, @RequestBody TrainerDTO dto) {
        log.info("管理端正在修改教练信息，id为：{}，修改信息为：{}", id, dto);
        ThrowUtils.throwIf(Objects.isNull(dto) ||
                        id == null ||
                        id <= 0 ||
                        !id.equals(dto.getId()),
                ReturnCodeEnum.PARAMS_ERROR);
        Trainer dbTrainer = trainerService.getById(id);
        String dbTrainerAvatar = dbTrainer.getAvatar();
        String avatar = dto.getAvatar();
        if (dbTrainerAvatar.contains(FileUploadBizEnum.TRAINER_AVATAR.getValue()) &&
                !avatar.equals(dbTrainerAvatar)) {
            cosManager.deleteObject(COSUtils.parseFileNameForTr(dbTrainerAvatar));
        }
        boolean result = trainerService.updateTrainer(dto);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "修改教练信息失败！");
        }
        return Result.ok(result);
    }

    @Operation(summary = "管理端：分页查询教练信息")
    @GetMapping("page")
    public Result<PageResult> getTrainerPage(TrainerPageQueryDTO dto) {
        log.info("管理端正在分页查询教练信息，查询参数为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);

        long current = dto.getCurrent();
        long size = dto.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 50 || current <= 0 || size <= 0, ReturnCodeEnum.PARAMS_ERROR);
        Page<TrainerVO> page = trainerService.getTrainerPage(dto);
        return page == null ? Result.ok(PageResult.builder()
                .records(Collections.emptyList())
                .total(0)
                .build()) : Result.ok(PageResult.builder()
                .records(page.getRecords())
                .total(page.getTotal())
                .build());
    }

    @Operation(summary = "管理端：根据id查询教练信息")
    @GetMapping("{id}")
    public Result<TrainerVO> getById(@PathVariable("id") Long id) {
        log.info("管理端正在根据id查询教练信息，id为：{}", id);
        ThrowUtils.throwIf(Objects.isNull(id) || id <= 0,
                ReturnCodeEnum.PARAMS_ERROR);

        TrainerVO trainerVO = trainerService.getByIdWithExpertise(id);
        if (Objects.isNull(trainerVO)) {
            throw new BusinessException(ReturnCodeEnum.NOT_FOUND_ERROR, "该教练信息不存在！");
        }

        return Result.ok(trainerVO);
    }

    @Operation(summary = "管理端：认证教练")
    @PutMapping("/{id}/{isIdentify}")
    public Result<Boolean> identify(@PathVariable("id") Long id,
                                    @PathVariable("isIdentify") Integer isIdentify) {
        log.info("管理端正在进行教练认证，教练id：{}", id);

        // 校验参数id是否合法
        ThrowUtils.throwIf(Objects.isNull(id) || id < 0, ReturnCodeEnum.PARAMS_ERROR, "教练id有误！");

        // 校验isIdentify参数是否合法
        ThrowUtils.throwIf(Objects.isNull(isIdentify) ||
                        !EmployeeConstant.EMP_IDENTIFY_LIST.contains(isIdentify)
                , ReturnCodeEnum.PARAMS_ERROR, "认证参数有误！");
        boolean result = trainerService.identifyTrainer(id, isIdentify);
        return Result.ok(result);
    }


    @Operation(summary = "管理端：获取所有教练")
    @GetMapping("all")
    public Result<List<Trainer>> getAll(){
        log.info("管理端正在获取所有教练信息");
        List<Trainer> list = trainerService.getBaseMapper().selectList(null);
        return Result.ok(list);
    }

}
